<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Modal } from 'ant-design-vue';

import {
  BankOutlined,
  BookOutlined,
  BuildOutlined,
  ClockCircleOutlined,
  CrownOutlined,
  DollarOutlined,
  ExperimentOutlined,
  FileTextOutlined,
  FireOutlined,
  HomeOutlined,
  LogoutOutlined,
  MoneyCollectOutlined,
  ReadOutlined,
  RobotOutlined,
  SafetyCertificateOutlined,
  SettingOutlined,
  ShopOutlined,
  TeamOutlined,
  UserOutlined,
  WalletOutlined,
  DisconnectOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons-vue';

import GlobalSearch from '../components/common/GlobalSearch.vue';
import NewUserGuide from '../components/guide/NewUserGuide.vue';
import { useWallet } from '../composables/useWallet';

const router = useRouter();
const route = useRoute();
const selectedKeys = ref<string[]>(['dashboard']);
const guideRef = ref();
const walletModalVisible = ref(false);

// 使用钱包 Composable
const {
  isConnected,
  isConnecting,
  currentAccount,
  accountBalance,
  shortAddress,
  isCorrectNetwork,
  networkStatus,
  connectWallet: connect,
  disconnectWallet,
  switchNetwork,
  refreshAccount,
} = useWallet();

watch(
  () => route.path,
  (path) => {
    const key = path.split('/').pop() || 'dashboard';
    selectedKeys.value = [key];
  },
  { immediate: true },
);

function handleMenuClick({ key }: { key: string }) {
  router.push(`/zhu-family/${key}`);
}

function connectWallet() {
  walletModalVisible.value = true;
}

function handleGuideFinish() {
  console.log('引导完成');
}

async function handleConnect() {
  await connect();
}

function handleDisconnect() {
  disconnectWallet();
  walletModalVisible.value = false;
}
</script>

<template>
  <a-layout class="zhu-family-layout">
    <!-- 顶部导航 -->
    <a-layout-header class="header">
      <div class="header-content">
        <div class="logo">
          <CrownOutlined style="font-size: 32px; color: white" />
          <h1>大明王朝 · 朱氏皇族治理中台</h1>
        </div>
        <div class="header-actions">
          <a-space :size="16">
            <GlobalSearch />
            <a-dropdown>
              <a-button type="text" style="color: white">
                <UserOutlined /> 宣德帝朱瞻基
              </a-button>
              <template #overlay>
                <a-menu>
                  <a-menu-item
                    key="profile"
                    @click="router.push('/zhu-family/profile')"
                  >
                    <UserOutlined /> 个人中心
                  </a-menu-item>
                  <a-menu-item key="settings">
                    <SettingOutlined /> 设置
                  </a-menu-item>
                  <a-menu-divider />
                  <a-menu-item key="logout">
                    <LogoutOutlined /> 退出
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
            <!-- 钱包连接按钮 -->
            <a-dropdown v-if="isConnected">
              <a-button type="text" style="color: white">
                <CheckCircleOutlined style="color: #52c41a" /> {{ shortAddress }}
              </a-button>
              <template #overlay>
                <a-menu>
                  <a-menu-item disabled>
                    <div style="padding: 8px 0">
                      <div style="font-size: 12px; color: #999">账户余额</div>
                      <div style="font-size: 14px; font-weight: 600">{{ accountBalance }} ETH</div>
                    </div>
                  </a-menu-item>
                  <a-menu-item disabled>
                    <div style="padding: 8px 0">
                      <div style="font-size: 12px; color: #999">网络状态</div>
                      <div style="font-size: 14px">{{ networkStatus }}</div>
                    </div>
                  </a-menu-item>
                  <a-menu-divider />
                  <a-menu-item key="refresh" @click="refreshAccount">
                    <WalletOutlined /> 刷新余额
                  </a-menu-item>
                  <a-menu-item v-if="!isCorrectNetwork" key="switch" @click="switchNetwork">
                    <WalletOutlined /> 切换网络
                  </a-menu-item>
                  <a-menu-item key="details" @click="connectWallet">
                    <SettingOutlined /> 钱包详情
                  </a-menu-item>
                  <a-menu-divider />
                  <a-menu-item key="disconnect" @click="handleDisconnect" danger>
                    <DisconnectOutlined /> 断开连接
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
            <a-button v-else type="text" style="color: white" @click="connectWallet" :loading="isConnecting">
              <WalletOutlined /> {{ isConnecting ? '连接中...' : '连接钱包' }}
            </a-button>
          </a-space>
        </div>
      </div>
    </a-layout-header>

    <a-layout>
      <!-- 侧边菜单 -->
      <a-layout-sider width="250" class="sider">
        <a-menu
          v-model:selected-keys="selectedKeys"
          mode="inline"
          :style="{ height: '100%', borderRight: 0 }"
          @click="handleMenuClick"
        >
          <a-menu-item key="dashboard">
            <CrownOutlined />
            <span>帝国首页</span>
          </a-menu-item>
          <a-menu-item key="genealogy" data-guide="genealogy">
            <TeamOutlined />
            <span>皇族世系</span>
          </a-menu-item>
          <a-menu-item key="governance" data-guide="governance">
            <BankOutlined />
            <span>朝政治理</span>
          </a-menu-item>
          <a-menu-item key="kingdom">
            <HomeOutlined />
            <span>藩国管理</span>
          </a-menu-item>
          <a-menu-item key="treasury">
            <MoneyCollectOutlined />
            <span>国库财政</span>
          </a-menu-item>
          <a-menu-item key="archive">
            <BookOutlined />
            <span>史官档案</span>
          </a-menu-item>
          <a-menu-divider />
          <a-menu-item-group title="数字祠堂" data-guide="shrine-group">
            <a-menu-item key="shrine" data-guide="shrine">
              <FireOutlined />
              <span>祖先纪念堂</span>
            </a-menu-item>
            <a-menu-item key="shrine-3d">
              <BuildOutlined />
              <span>3D虚拟祠堂</span>
            </a-menu-item>
            <a-menu-item key="timecapsule">
              <ClockCircleOutlined />
              <span>时间胶囊</span>
            </a-menu-item>
          </a-menu-item-group>
          <a-menu-divider />
          <a-menu-item-group title="家族学堂" data-guide="academy">
            <a-menu-item key="academy/knowledge">
              <BookOutlined />
              <span>知识库</span>
            </a-menu-item>
            <a-menu-item key="academy/courses">
              <ReadOutlined />
              <span>课程学习</span>
            </a-menu-item>
            <a-menu-item key="academy/stories">
              <FileTextOutlined />
              <span>家族故事</span>
            </a-menu-item>
            <a-menu-item key="ai-heir">
              <RobotOutlined />
              <span>AI Heir</span>
            </a-menu-item>
          </a-menu-item-group>
          <a-menu-divider />
          <a-menu-item-group title="区块链功能">
            <a-menu-item key="blockchain/registry">
              <TeamOutlined />
              <span>家族注册</span>
            </a-menu-item>
            <a-menu-item key="blockchain/members">
              <UserOutlined />
              <span>成员管理</span>
            </a-menu-item>
            <a-menu-item key="blockchain/governance">
              <FileTextOutlined />
              <span>链上治理</span>
            </a-menu-item>
            <a-menu-item key="blockchain/nft">
              <SafetyCertificateOutlined />
              <span>NFT 铸造</span>
            </a-menu-item>
            <a-menu-item key="blockchain/wallet-generator">
              <WalletOutlined />
              <span>钱包生成器</span>
            </a-menu-item>
          </a-menu-item-group>
          <a-menu-divider />
          <a-menu-item-group title="高级功能">
            <a-menu-item key="wealth">
              <DollarOutlined />
              <span>财富传承</span>
            </a-menu-item>
            <a-menu-item key="gene-privacy">
              <ExperimentOutlined />
              <span>基因隐私</span>
            </a-menu-item>
            <a-menu-item key="legal">
              <SafetyCertificateOutlined />
              <span>法律合规</span>
            </a-menu-item>
            <a-menu-item key="business">
              <ShopOutlined />
              <span>商业协作</span>
            </a-menu-item>
          </a-menu-item-group>
        </a-menu>
      </a-layout-sider>

      <!-- 主内容区 -->
      <a-layout-content class="content">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <component :is="Component" />
          </transition>
        </router-view>
      </a-layout-content>
    </a-layout>

    <!-- 新手引导 -->
    <NewUserGuide
      ref="guideRef"
      :auto-start="true"
      @finish="handleGuideFinish"
    />

    <!-- 钱包连接弹窗 -->
    <a-modal
      v-model:open="walletModalVisible"
      title="🔗 区块链钱包"
      :footer="null"
      width="500px"
      centered
    >
      <!-- 未连接状态 -->
      <div v-if="!isConnected" class="wallet-connect-content">
        <div class="wallet-info">
          <WalletOutlined style="font-size: 64px; color: #1890ff; margin-bottom: 16px" />
          <h3>连接到 FamilyChain</h3>
          <p style="color: #666; margin-bottom: 24px">
            连接您的 MetaMask 钱包以使用区块链功能
          </p>
          
          <a-space direction="vertical" style="width: 100%" :size="16">
            <a-button
              type="primary"
              size="large"
              block
              :loading="isConnecting"
              @click="handleConnect"
            >
              <WalletOutlined /> 连接 MetaMask
            </a-button>
            
            <a-alert
              message="温馨提示"
              description="请确保已安装 MetaMask 浏览器插件，并切换到正确的网络"
              type="info"
              show-icon
            />
          </a-space>
        </div>
      </div>

      <!-- 已连接状态 -->
      <div v-else class="wallet-connected-content">
        <a-result status="success" title="钱包已连接">
          <template #icon>
            <CheckCircleOutlined style="color: #52c41a" />
          </template>
          
          <template #extra>
            <a-descriptions bordered :column="1" size="small">
              <a-descriptions-item label="账户地址">
                <a-tag color="blue" style="font-family: monospace">
                  {{ shortAddress }}
                </a-tag>
              </a-descriptions-item>
              <a-descriptions-item label="完整地址">
                <div style="font-family: monospace; font-size: 12px; word-break: break-all">
                  {{ currentAccount }}
                </div>
              </a-descriptions-item>
              <a-descriptions-item label="账户余额">
                <span style="font-weight: 600; color: #1890ff">
                  {{ accountBalance }} ETH
                </span>
              </a-descriptions-item>
              <a-descriptions-item label="网络状态">
                <a-tag :color="isCorrectNetwork ? 'success' : 'error'">
                  {{ networkStatus }}
                </a-tag>
              </a-descriptions-item>
            </a-descriptions>
            
            <a-space style="margin-top: 16px; width: 100%" direction="vertical">
              <a-button block @click="refreshAccount">
                <WalletOutlined /> 刷新账户信息
              </a-button>
              
              <a-button
                v-if="!isCorrectNetwork"
                block
                type="primary"
                @click="switchNetwork"
              >
                切换到正确网络
              </a-button>
              
              <a-button block danger @click="handleDisconnect">
                <DisconnectOutlined /> 断开连接
              </a-button>
            </a-space>
          </template>
        </a-result>
      </div>
    </a-modal>
  </a-layout>
</template>

<style scoped lang="scss">
.zhu-family-layout {
  min-height: 100vh;
}

.header {
  padding: 0 24px;
  background: linear-gradient(135deg, #b8860b 0%, #daa520 100%);
  box-shadow: 0 2px 8px rgb(0 0 0 / 15%);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
}

.logo {
  display: flex;
  gap: 12px;
  align-items: center;

  h1 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: white;
  }
}

.sider {
  background: white;
  box-shadow: 2px 0 8px rgb(0 0 0 / 5%);
}

.content {
  min-height: calc(100vh - 64px);
  padding: 24px;
  background: #f5f5f5;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

// 钱包连接弹窗样式
.wallet-connect-content,
.wallet-connected-content {
  padding: 24px 0;
  
  .wallet-info {
    text-align: center;
    
    h3 {
      font-size: 20px;
      font-weight: 600;
      margin-bottom: 8px;
    }
  }
}

:deep(.ant-result) {
  padding: 24px 0;
}

:deep(.ant-descriptions-item-label) {
  font-weight: 500;
}
</style>
